<template>
  <div class="list">
     
      <van-nav-bar
        title="列表"
        class="list-nav"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      >
      </van-nav-bar>

    <!-- 宫格 -->
    <van-grid :column-num="4">
      <van-grid-item
        v-for="value in categories"
        :key="value.id"
        :icon="value.coverImage | dalImg"
        :text="value.name"
        @click="show(value.id)"
      />
    </van-grid>

    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-card
        :num="value.amount"
        v-for="value in products"
        :key="Math.random() * 1000 + value"
        :price="value.price.toFixed(2)"
        :title="value.name"
        :origin-price="value.price"
        :thumb="value.coverImage | dalImg"
        @click-thumb="toDetail(value.id)"
      />
    </van-list>
  </div>
</template>
<script>
import { loadProductsAPI } from "../services/products";
import { loadCategoriesAPI } from "../services/categories";
export default {
  data() {
    return {
      products: [],
      categories: [],
      page: 1,
      loading: false,
      finished: false,
    };
  },
  async created() {
    const resCategories = await loadCategoriesAPI();
    this.categories = resCategories.data;
  },
  methods: {
    //退回
    onClickLeft() {
      this.$router.go(-1);
    },
    async show(id) {
      const resProducts = await loadProductsAPI(id);
      this.products = resProducts.data;
    },

    async loadMore() {
      this.loading = true; // 设置为加载中
      const res = await loadProductsAPI(this.page);
      if (res.data.length == 0) {
        this.finished = true;
      }
      this.page++;
      this.products.push(...res.data);
      this.loading = false;
    },
    onLoad() {
      this.loadMore();
    },
    toDetail(id) {
      this.$router.push({
        name: "Detail",
        query: {
          id,
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.list {
  .list-nav {
    position: sticky;
    top: 0;
    z-index: 9;
  }
}
</style>